
load("js/luaclient.js")

var v4_citic_debit_java_funcs = {

    openHomePage: function () {
        var html = get("https://i.bank.ecitic.com/perbank6/signIn.do");
        storeDataToFile(context, html, "login_1.txt");
    },
    checkControlAvailable: function () {
        return true;
    },
    checkTargetWebsiteAvailable: function () {
        return true;

    },
    //检查代理是否可用
    checkProxyAvailable: function () {
        var checkPrxoy = function () {
            return is_exist_by_id("certListCite");
        }
        var getErrorMsg = function () {
            return "代理ip异常";
        }
        return assertTrueOrThrowException("", checkPrxoy, getErrorMsg)
    },
    login: function () {
        inputBaseCitic();
        inputImgCitic();
        inputSmsCitic();
    },
    needRefreshHomePageOrNot: function () {
        return equals(context.get("currentErrorCode"), BALO_99602_50)
    },
    needResetEnvironment: function () {
        return false;
    },
    //抓取过程
    crawl: function () {
        crawlCitic();
    },
    exitLogin: function () {
    }

};


/**
 * ------------------------------------------------------------------------------------
 * start--------------抓取业务方法--------------start
 * ------------------------------------------------------------------------------------
 */


var count = 0 ;
function inputBaseCitic()  {
    var checkInputFunc = function () {
        var username = getLoginParams(context)[0];
        var password = context.get(LUA_TASK_TOKEN);
        logger.info("原始密码长度"+password.length);
        if(password.length>20){
            password = password.substring(0, 20) ;
            logger.info("处理密码长度"+password.length);
        }

        var startTime = System.currentTimeMillis();
        //输入用户名密码
        var path = luaFuncs.inputnameAndpassword(username, password);
        var endTime = System.currentTimeMillis() - startTime;
        logger.info("任务" + context.get(Constants.TASK_KEY) + "窗口时间：" + endTime);
        logger.info("登录返回值"+path);
        var params = path.split("|") ;
        if(params.length == 2){
            var inputLength = params[1].length ;
            var passwordLength = password.length ;
            if (inputLength !== passwordLength){
                logger.error("密码输入异常，输入的长度不等于真正的长度");
                return false;
            }
        }

        context.put(TASK_IMG_PATH, params[0]) ;
        var message = luaFuncs.clickLogin() ;
        logger.info("中信银行登录提示"+message);
        if(message!==null && message.contains("请输入4位验证码")){
            context.put("imgflag", "true") ;
        }
        return true;
    }
    var getErrorMsg = function () {
        return "密码因控件输入错误";
    }
    return assertTrueOrThrowException("", checkInputFunc, getErrorMsg);
}


function inputImgCitic()  {
    var loginResult= {}
    var checkImgResult = function (loginResult) {
        loginResult.errorMsg="验证码处理发生错误";
        var imgflag = context.get("imgflag") ;
        if(StringUtils.equals("true", imgflag)){

            logger.info(" 人工打码开始");

            context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
            var code = waitImgCodeBySecondsByJs(context,120,true,3);

            if (StringUtils.isBlank(code) || code.length < 4) {
                logger.info("打码位数不足四位，手动补足 {}", code);
                code = "1234";
            }
            logger.info(code);
            logger.info("输入验证码开始");
            luaFuncs.setCode(code);// 输入验证码
            Thread.sleep(500);
            logger.info("点击登录按钮开始");
            var message = luaFuncs.clickLogin() ;
            if(message!==null && message.contains("验证码错误")){
                return false ;
            }
        }
        Thread.sleep(2000);
        var html = luaFuncs.getHtmlGb() ;
        storeDataToFile(context,html, "login_2.txt");
        for(var i=3 ; i<=5 ;i++){
            if(html.contains("正在查询用户名")){
                Thread.sleep(5000);
                html = luaFuncs.getHtmlGb() ;
                storeDataToFile(context,html, "login_"+i+".txt");
            }else{
                break ;
            }
            if(i == 5){//响应3次没响应网站繁忙
                loginResult.errorMsg = "系统繁忙，请稍候再试(登录前)";
                return false
            }
        }
        var flag = getMainHtml(html) ;
        if(!flag){
            var doc = Jsoup.parse(html) ;
            var title = doc.select("title").text() ;
            if(StringUtils.equals("网银引导流程", title))
            {
                loginResult.errorMsg = "请登录官网设置网银引导流程";
                return false;
            }
            if(doc.select("[class=errorReason]") == null || doc.select("[class=errorReason]").size() == 0)
            {
                loginResult.errorMsg = "网站繁忙，请稍后再试";
                return false;
            }
            var error = doc.select("[class=errorReason]").first().text() ;
            logger.info("中信银行taskKey = {} 登录失败",context.get(LUA_TASK_KEY));
            loginResult.errorMsg = error;
            return false
        }
        var accountNos = context.get("accountNos");
        if(accountNos.size()==0){
            loginResult.errorMsg = "未获取到卡片信息，请登录官网绑定卡片";
            return false
        }
        return true;
    }
    var getErrorMsg = function (loginResult) {
        return loginResult.errorMsg;
    }
    return assertTrueOrThrowException(loginResult, checkImgResult, getErrorMsg);




}
function inputSmsCitic(){
    var isCorrectFunc = function () {
        return true
    };
    var getErrorMsgFunc = function () {
        return ""
    };
    return assertTrueOrThrowException("", isCorrectFunc, getErrorMsgFunc)
}

function crawlCitic() {
    crawlCiticDebit();
    // crawlCitciCredit();
}

function getAccuountInfoForThreeTimes(accountNo) {
    var EMP_SID = context.get("EMP_SID");
    var accountNos = context.get("accountNos");
    for(var i =0;i<2;i++){
        logger.info("开始访问账户信息页面");
        var html = ajax_get(
            "https://i.bank.ecitic.com/perbank6/pb1110_query_detail.do?EMP_SID=" + EMP_SID + "&accountNo=" + accountNo + "&index=0ff0");
        storeDataToFile(context,html, count+"_card.txt");
        if(html.contains("获取")&& html.contains("失败")){
            logger.info("中信借记卡获取信息失败，继续请求账户页面")
            Thread.sleep(1500)
        }else {
            return html
        }
    }
    if(i >= 2){
        return "WRONGACCOUNT";
    }
}


/**
 * 借记卡抓取
 */
function crawlCiticDebit() {
    logger.info("Citic taskKey = {} 开始抓取信用卡",   context.get(LUA_TASK_KEY) )
    var EMP_SID = context.get("EMP_SID");
    var accountNos = context.get("accountNos");
    var creditBanks = new ArrayList();
    for each(var accountNo in accountNos){
        var data = new CreditCardAllData();
        // 访问账户信息页面
        var html = getAccuountInfoForThreeTimes(accountNo);
        if(html.contains("WRONGACCOUNT")){
            throw new BankException(BankConstants.BACR_21301_10, "账户信息获取失败");
        }
        getAccountInfo(html, data, accountNo);
        //访问请求参数页面
        logger.info("开始访问请求参数页面");
        html = ajax_get(
            "https://i.bank.ecitic.com/perbank6/trans_3063s.do?EMP_SID=" + EMP_SID + "&accountNo=" + accountNo + "&selectSubAccount=null");
        storeDataToFile(context,html, "params"+accountNo+".txt");
        //访问每个月流水
        logger.info("开始访问账单流水页面");
        getBillHtml(html, accountNo, EMP_SID,data);
        creditBanks.add(data);
        count++ ;
    }
    context.put("debit_data",creditBanks);
}



/**
 * 登录后的页面判断是否登录成功
 * @param html
 */
function getMainHtml(html){
    getLoginEMP_SID(html) ;
    var doc = Jsoup.parse(html) ;
    var name = doc.select("[class=userName]").text() ;
    context.put("name", name) ;
    if(!html.contains("尊敬的")){
        return false ;
    }
    return true ;
}
function getLoginEMP_SID( content) {
    var express1 = "EMP_SID=[A-Z]{0,50}";
    var express2 = ".*javascript:subDetailFunc\('(\\d+)'.*" ;
    var EMP_SID = null ;
    var accountNos = new ArrayList() ;
    var accountNo = null ;
    var matcher = Pattern.compile(express1).matcher(content);
    if (matcher.find()) {
        EMP_SID = matcher.group(0).replaceAll("EMP_SID=", "");
        logger.info("EMP_SID="+EMP_SID) ;
    }
    context.put("EMP_SID", EMP_SID) ;
    //解析出帐号参数
    var doc = Jsoup.parse(content);
    var elements=doc.select(".newCardFontRed");
    for each( var element in elements){
        if(element!=null&&element.text()!=""){
            if(element.text().contains("借记卡")){
                 accountNo=element.child(0).attr("id").replace("level","");
                accountNos.add(accountNo) ;
            }
        }
    }
    context.put("accountNos", accountNos) ;
}
/**
 * 解析账户信息（子账户信息）
 *
 * @param html
 * @param data
 */
function getAccountInfo( html,  data,  accountNo) {
    try {
        var creditCardTimeDeposits = new ArrayList();
        var doc = Jsoup.parse(html);
        var eles = doc.select("table").select("tr");
        var balance = null ;
        if (eles.size() > 1) {
            for each(var eleTr in eles){
                var eleTd = eleTr.select("td") ;
                if(eleTd.size() == 11){
                    var creditCardTimeDeposit = new CreditCardTimeDeposit();
                    var deposit_type = eleTd.get(0).text().replaceAll("\u00A0", "");// 活期
                    if(deposit_type.contains("类型")){
                        continue ;
                    }
                    var currency_type = eleTd.get(1).text().replaceAll("\u00A0", "");// 人名币
                    var period = eleTd.get(3).text().replaceAll("\u00A0", "");// 期限// 活期
                    balance = eleTd.get(7).text().replaceAll("\u00A0", "").replaceAll(",", "");// 可用余额// 537.41
                    var interest = eleTd.get(4).text().replaceAll("%", "").replaceAll("\u00A0", "");// 执行利率
                    var deposit_date = eleTd.get(5).text().replaceAll("\u00A0", "");//
                    var due_date = eleTd.get(6).text().replaceAll("\u00A0", "").replaceAll("--", "");
                    creditCardTimeDeposit.setCurrencyType(CreditResultUtil.convertCurr(currency_type));
                    creditCardTimeDeposit.setDepositType(deposit_type + "储蓄");
                    if(deposit_date!=null&&deposit_date!=""){
                        creditCardTimeDeposit.setDepositDate(yyyy_MM_dd_PARSER.parse(deposit_date));
                    }
                    if(due_date!=null&&due_date!=""){
                        creditCardTimeDeposit.setDueDate(yyyy_MM_dd_PARSER.parse(due_date));
                    }
                    creditCardTimeDeposits.add(creditCardTimeDeposit);
                    if(!StringUtils.isEmpty(balance)){
                        creditCardTimeDeposit.setBalance(new BigDecimal(balance));
                    }
                    if(!StringUtils.isEmpty(interest)){
                        creditCardTimeDeposit.setInterest(new BigDecimal(interest).divide(new BigDecimal("100")));
                    }

                }
            }
        }
        data.setDeposits(creditCardTimeDeposits);
        if(accountNo.length>5){
            data.setCardNum(accountNo.substring(accountNo.length-4,accountNo.length));
        }
        if(accountNo!=""&&accountNo!=null){
            accountNo=accountNo.replace(accountNo.substring(4,accountNo.length()-4),"********");
        }
        data.setFullCardNum(accountNo);
        data.setCardType("借记卡");
        data.setBankName("中信银行");
        data.setCardId(UUID.randomUUID().toString());
        data.setCashBalance(null);
        data.setCashLimit(null);
        data.setCreditLimit(null);
        balance = doc.select("[id=balance]").val().replaceAll(",", "") ;
        if(!StringUtils.isEmpty(balance)){
            data.setBalance(new BigDecimal(balance));
        }
    } catch (e) {
        logger.error("中信储蓄卡账户信息页面解析异常", e);
    }
}
/**
 * 获取流水信息的页面
 * @param html
 * @param accNo
 * @param EMP_SID
 * @throws Exception
 */
function getBillHtml(html,accNo, EMP_SID, card)  {
    try {
        var fst = getFirstMonthFirstDay();
        var lst = getBeforMonthLast();
        var bills = card.getBills();
        if (bills == null) {
            bills = new ArrayList();
        }
        for(var i=0 ; i<12 ; i++){
            var beginDate = fst.get(i);
            var endDate = lst.get(i);
            var bill = new BillAllData() ;
            bill.setBankName("中信银行");
            var sb = new StringBuilder(beginDate) ;
            var billdate = sb.insert(4, "-").insert(7,"-").toString() ;
            bill.setBillDate(yyyy_MM_dd_PARSER.parse(billdate));
            bill.setBillMonth(billdate.substring(0, 7));
            bill.setBillId(UUID.randomUUID().toString());
            bill.setBillType("DONE");
            var url = "https://i.bank.ecitic.com/perbank6/pb1310_account_detail.do?EMP_SID=" + EMP_SID + "&payAcctxt=" + accNo + getParamterUrlInfo(html, accNo, beginDate, endDate) ;
            var html1 = ajax_get(url);
            storeDataToFile(context,html1, count+"_card_"+beginDate+".txt");
            logger.info("开始解析" + count+"_card_"+beginDate+".txt" +"月份的流水");
            var expenses = getBillInfo(html1, accNo) ;
            bill.setShoppingSheets(expenses) ;

            bill.setCashLimit(null);
            bill.setCreditLimit(null);
            bill.setInterest(null);
            bill.setLastBalance(null);
            bill.setLastPayment(null);
            bill.setMinPayment(null);
            bill.setNewBalance(null);
            bill.setNewCharges(null);
            bill.setUsdCashLimit(null);
            bill.setUsdCreditLimit(null);
            bill.setUsdInterest(null);
            bill.setUsdLastBalance(null);
            bill.setUsdLastPayment(null);
            bill.setUsdMinPayment(null);
            bill.setUsdNewBalance(null);
            bill.setUsdNewCharges(null);
            bills.add(bill) ;
            Thread.sleep(1000);
        }
        //开卡时间
        card.setOpenTime(yyyyMMdd_PARSER.parse(context.get("openDate")));
        card.setNameOnCard(context.get("name"));
    }catch (e){
        logger.error("中信借记卡 解析异常",e);
    }


}
/**
 * 解析流水信息页面
 * @param html
 * @param accNo
 * @return
 */
function getBillInfo( html, accNo){
    var expenses = new ArrayList() ;
    try {
        accNo = accNo.substring(accNo.length-4,accNo.length) ;
        var i = 1 ;
        var  doc = Jsoup.parse(html);
        var elements=doc.select("table#resultTable1>tbody").first().select("tr");
        for each (var element in elements){

            //交易时间
            var transTime=element.select("td").get(0).text();
            //收入金额 (拼接负号)
            var madeMoney=element.select("td").get(1).text().replaceAll("￥|,|\\u00A0","");

            // 支出金额
            var expenMoney=element.select("td").get(2).text().replaceAll("￥|,|\\u00A0","");

            // 账户余额
            var balance=element.select("td").get(3).text().replaceAll("￥|,|\\u00A0","");
            //对方名称
            var name=element.select("td").get(4).text();
            //对方账号
            var oppositeNo=element.select("td").get(5).text();
            // 摘要 描述
            var description=element.select("td").get(6).text();

            var expense = new Expense() ;
            var category  = judgeBillCategorym(description) ;
            if(StringUtils.isBlank(category)){
                category ="SHOPPING";
            }
            expense.setCardNum(accNo);
            expense.setCategory(category);
            expense.setCurrencyType("CNY");
            expense.setDescription(description);
            expense.setId(UUID.randomUUID().toString());
            expense.setNameOnOppositeCard(name);
            expense.setOppositeBank(name);
            expense.setOppositeCardNo(oppositeNo);
            expense.setOrderIndex(i++);
            expense.setPostDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transTime));
            expense.setTransAddr("");
            expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transTime));
            expense.setBalance(new BigDecimal(balance));
            expense.setAmountMoney(new BigDecimal(madeMoney.contains("--")?expenMoney:"-"+madeMoney));
            expenses.add(expense) ;
        }
    } catch (e) {
        logger.error("中信储蓄卡流水信息页面解析异常", e);
    }
    return expenses ;
}
/**
 * 获取流水信息的url
 * @param html
 * @param accNo
 * @param beginDate
 * @param beginDate
 * @param endDate
 * @return
 */
function getParamterUrlInfo(html, accNo, beginDate, endDate) {
    var doc = Jsoup.parse(html);
    var eles = doc.select("input");
    try{
        var judFrozenSFlag = eles.get(0).val();
        var openDate = eles.get(1).val();
        var qcAmt = eles.get(2).val();
        var creditBalance = eles.get(3).val();
        var extendFlag = eles.get(4).val();
        var subAccountNo = eles.get(5).val();
        var frozenSFlag = eles.get(6).val();
        var lossFlag = eles.get(7).val();
        var balance = eles.get(8).val();
        var originalBalance = eles.get(9).val();
        var saveType = eles.get(10).val();
        var hostAccType = eles.get(11).val();
        var currencyType = eles.get(12).val();
        var accrualStartDate = eles.get(13).val();
        var savePeriod = eles.get(14).val();
        var interestRate = eles.get(15).val();
        var forzenAmt = eles.get(16).val();
        var accountNo = eles.get(17).val();
        var jurForzenAmt = eles.get(18).val();
        var accrualEDate = eles.get(19).val();
        var recordState = eles.get(20).val();

        var url = "&isubAccInfo.judFrozenSFlag=" + judFrozenSFlag + "&isubAccInfo.openDate=" + openDate
            + "&isubAccInfo.qcAmt=" + qcAmt + "&isubAccInfo.creditBalance=" + creditBalance
            + "&isubAccInfo.extendFlag=" + extendFlag + "&isubAccInfo.subAccountNo=" + subAccountNo
            + "&isubAccInfo.frozenSFlag=" + frozenSFlag + "&isubAccInfo.balance=" + balance
            + "&isubAccInfo.lossFlag=" + lossFlag + "&isubAccInfo.originalBalance=" + originalBalance
            + "&isubAccInfo.saveType=" + saveType + "&isubAccInfo.hostAccType=" + hostAccType
            + "&isubAccInfo.currencyType=" + currencyType + "&isubAccInfo.accrualStartDate=" + accrualStartDate
            + "&isubAccInfo.savePeriod=" + savePeriod + "&isubAccInfo.interestRate=" + interestRate
            + "&isubAccInfo.forzenAmt=" + forzenAmt + "&isubAccInfo.accountNo=" + accountNo
            + "&isubAccInfo.jurForzenAmt=" + jurForzenAmt + "&isubAccInfo.accrualEDate=" + accrualEDate
            + "&isubAccInfo.recordState=" + recordState + "&stdpriacno=" + accountNo + "&accountNo=" + accNo
            + "&stdessbgdt="+beginDate+"&stdesseddt="+endDate+"&stdesssbno=&CashFlag=&recordStart=" + 1
            + "&recordNum=" + 50
            + "&std400chnn=&std400dcfg=&std400pgqf=N&std400pgtk=&std400pgts=&stdudfcyno=001&opFlag=0&stkessmnam=&largeAmount=&queryType=special&targetPage=21&beginAmt=&endAmt=&recordSize="
            + 0 + "&queryDays=&startPageFlag=&pageType=2&beforePageMap=";
        context.put("openDate", openDate) ;
        return url;
    }catch (e){
        logger.error("中信借记卡 获取借假卡列表失败 停止抓取",e)
        return "";
    }

}
/**
 * 获取之前12个月的第一天:格式:2016-12-01
 *
 * @return
 */
function getFirstMonthFirstDay() {

    var lst = new ArrayList();
    var calendar = new GregorianCalendar();
    var dfdate = new SimpleDateFormat("yyyyMMdd");
    for (var i = 0; i < 12; i++) {
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1 * i);
        var gcLast = Calendar.getInstance();
        gcLast.setTime(calendar.getTime());
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        lst.add(dfdate.format(gcLast.getTime()));
    }
    return lst;
}

/**
 * 获取之前12个月的最后一天,格式:2016-12-31,本月返回今天
 *
 * @return
 */
function getBeforMonthLast() {

    var lst = new ArrayList();
    var calendar = new GregorianCalendar();
    var dfdate = new SimpleDateFormat("yyyyMMdd");
    for (var i = -1; i < 11; i++) {
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1 * i);
        var gcLast =  Calendar.getInstance();
        gcLast.setTime(calendar.getTime());
        gcLast.set(Calendar.DATE, 1);
        gcLast.add(Calendar.DATE, -1);
        if (gcLast.getTime().after(new Date())) {
            lst.add(dfdate.format(new Date()));
        } else {
            lst.add(dfdate.format(gcLast.getTime()));
        }
    }
    return lst;
}

/**
 * 根据描述判断类型
 * @param description
 * @return
 */
function judgeBillCategorym(description){
    if (StringUtils.isNotBlank(description)) {
        if (description.contains("工资")) {
            return "SALARY";
        }else if (description.contains("奖金")) {
            return "BONUS";
        }else if (description.contains("利息")||description.contains("结息")) {
            return "ACCRUAL";
        }else if (description.contains("存现")) {
            return "DEPOSIT";
        }else if (description.contains("转账")) {
            return "TRANSFER";
        }else if (description.contains("借贷")) {
            return "LOANS";
        }else if (description.contains("冲账")) {
            return "REVERSE";
        }else if(description.contains("退款")){
            return "REFUND";
        }else if(description.contains("收益")){
            return "EARNINGS";
        }else if(description.contains("报销")){
            return "CLAIM";
        }else if(description.contains("取现")){
            return "WITHDRAW";
        }else if(description.contains("手续费")){
            return "HANDLINGFEE";
        }else if(description.contains("转账")){
            return "TRANSFER";
        }else if(description.contains("还贷")||description.contains("还款")){
            return "REPAYMENT";
        }else if(description.contains("理财")){
            return "FINANCE";
        }else if(description.contains("消费")||description.contains("支付")){
            return "CONSUMPTION";
        }else if(description.contains("房租")){
            return "RENT";
        }else if(description.contains("公积金")){
            return "FUND";
        }else if(description.contains("社保")){
            return "SOCIALSECURITY";
        }else if(description.contains("通讯费")){
            return "COMMUNICATIONFEE";
        }else if(description.contains("生活费")){
            return "LIVINGEXPENSE";
        }else if(description.contains("其他收入")||description.contains("S")){
            return "OTHERREVENUE";
        }else if(description.contains("其他支出")){
            return "OTHEREXPENSE";
        }else{
            return "OTHERFEE";
        }
    }else{
        return "CONSUMPTION";
    }
}

/**
 * 信用卡抓取
 */

function crawlCitciCredit() {
    logger.info("Citic taskKey ={} 开始抓取信用卡信息",context.get(LUA_TASK_KEY))
    var list=new ArrayList();
    context.put("credit_data", list);
    var EMP_SID = context.get("EMP_SID");
    var accountNos = context.get("accountNos");
    logger.info("Citic taskKey ={} 开始获取卡号列表",context.get(LUA_TASK_KEY))
    var cardListHtml=ajax_get("https://i.bank.ecitic.com/perbank6/pb1110_my_creditcard.do?EMP_SID="+EMP_SID);
    storeDataToFile(context,cardListHtml, "creditCardList.html");
    var cardListDoc = Jsoup.parse(cardListHtml);//一个tr是一个账户
    var cardListArr = new ArrayList();
    var cardElement= cardListDoc.select(".whiteColor")
    if(cardElement!=null && cardElement!=undefined && cardElement.size()>0){
        for (var j = 0; j < cardElement.size(); j++) {
            var cardInfoElement= cardElement.get(i)
            //javascript:subCrdDetailFunc('4033920033997406','4');
            var onclikInfo= cardInfoElement.select(".wid_jia").attr("onclick");
            logger.info("@@@@@@@@@@@@@@@@@@" + onclikInfo);
            if(StringUtils.isNotBlank(onclikInfo)){
                var cardInfo= onclikInfo.split("Func('");
                logger.info(cardInfo[0])
                logger.info(cardInfo[1])
                if(cardInfo.length>1) {
                    var cardNo=cardInfo[1].split("',")[0]
                    cardListArr.add(cardNo);//这里也可加上credit_limit
                }
            }
        }
    }else {
        logger.info("Citic taskKey ={} 获取卡列表为空，停止抓取信用卡信息",context.get(LUA_TASK_KEY))
        return
    }
    if(cardListArr.size()==0){
        logger.info("Citic taskKey ={} 获取卡列表为空，停止抓取信用卡信息",context.get(LUA_TASK_KEY))
        return;
    }
    for(var i=0;i<cardListArr.size();i++){
        var creditCardAllData = new CreditCardAllData();
        var cardNo = cardListArr.get(i);
        crawlCitciCreditBasicInfo(EMP_SID,cardNo,creditCardAllData);
        crawlCitciCreditUndoneBill(EMP_SID,cardNo,creditCardAllData);
        crawlCitciCreditDoneBill(EMP_SID,cardNo,creditCardAllData);
        list.add(creditCardAllData)
    }

}
/**
 *抓取信用卡基本信息
 * @param empSid
 * @param cardno
 * @param creditCardAllData
 */
function crawlCitciCreditBasicInfo(empSid,cardno,creditCardAllData) {
    logger.info("Citic taskKey ={} 开始抓取信用卡用户信息",context.get(LUA_TASK_KEY))
    ///perbank6/pb5110_accInfQry.do?EMP_SID=HXAMFDBMAAGKFSIXBYDJEUFCDJELBYBEJVHECDER&accountNo=4033920033997406&tempData=0&currencyType=01&crdCurr=001&OpFlag=
    try {
        var basicInfoHtml= ajax_get("https://i.bank.ecitic.com/perbank6/pb5110_accInfQry.do?EMP_SID="+empSid+"&accountNo="+cardno+"&tempData=0&currencyType=01&crdCurr=001&OpFlag=")
        storeDataToFile(context,basicInfoHtml, "basicInfo.html");
        var basicInfoDoc= Jsoup.parse(basicInfoHtml);
        var credit_limit=basicInfoDoc.select("tr.bg_white_color:nth-child(1) > td:nth-child(2)").get(0).text().replaceAll(",","");
        var balance=basicInfoDoc.select("tr.bg_white_color:nth-child(1) > td:nth-child(3)").get(0).text().replaceAll(",","");
        var cashBalance=basicInfoDoc.select("tr.bg_white_color:nth-child(1) > td:nth-child(4)").get(0).text().replaceAll(",","");
        var lastpayment_due_date=basicInfoDoc.select("tr.bg_white_color:nth-child(1) > td:nth-child(6)").get(0).text();
        var last_payment=basicInfoDoc.select("tr.bg_white_color:nth-child(1) > td:nth-child(7)").get(0).text();
        var newBalance=basicInfoDoc.select("tr.bg_white_color:nth-child(1) > td:nth-child(5)").get(0).text().replaceAll(",","");
    }catch (e){
        logger.info("Citic taskKey ={} 解析账单信息失败，继续抓取",context.get(LUA_TASK_KEY));
    }
    creditCardAllData.setBankName("CITIC");
    creditCardAllData.setCardId(UUID.randomUUID().toString());
    creditCardAllData.setCardType("信用卡");
    creditCardAllData.setCardNum(cardno.substring(cardno.length() - 4, cardno.length()));
    creditCardAllData.setFullCardNum(cardno);
    creditCardAllData.setBalance(CreditResultUtil.StringToBigDecimal(balance));
    // creditCardAllData.setNameOnCard();
    creditCardAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(credit_limit));
    creditCardAllData.setCashBalance(CreditResultUtil.StringToBigDecimal(cashBalance));
}
/**
 * 抓取未出账单
 * @param empSid
 * @param cardNo
 * @param creditCardAllData
 */
function crawlCitciCreditUndoneBill(empSid,cardNo,creditCardAllData) {
    logger.info("Citic taskKey ={} 开始抓取信用卡未出账单",context.get(LUA_TASK_KEY))
    var param = new HashMap();
    param.put("accountNo", cardNo);
    param.put("currencyType", "001");
    param.put("startNo", "0000000001");
    param.put("crdRecordItem", "0000000010");
    param.put("crtDataType", "00000002");
    param.put("crtOutputType", "ZCC0306O1");
    param.put("sFrnCyno", "014");
    param.put("condInf", "");
    var unbillHtml= ajax_post("https://i.bank.ecitic.com/perbank6/pb5120_unBillQryNew.do?EMP_SID=" + empSid, param);
    storeDataToFile(context,unbillHtml, "unbill.html");
    var unbillDoc= Jsoup.parse(unbillHtml);
    // TODO 这里还没完成
    // unbillDoc.select("");

}
/**
 * 抓取已出账单
 * @param empSid
 * @param cardNo
 * @param creditCardAllData
 */
function crawlCitciCreditDoneBill(empSid,cardNo,creditCardAllData) {
    logger.info("Citic taskKey ={} 开始抓取信用卡已出账单",context.get(LUA_TASK_KEY))
    //查询可以查询的月份
    //https://i.bank.ecitic.com/perbank6/pb5130_returnOtherMonth.do?EMP_SID=JGDTCNCCFHAWGTFYCMGVAOEAGUBVDSEGCQHQFSEL
    var monthParam = new HashMap();
    //accountNo=4033920033997406&currencyType1=
    monthParam.put("accountNo", cardNo);
    monthParam.put("currencyType1", "");
    var queryMonthsHtml= ajax_post("https://i.bank.ecitic.com/perbank6/pb5130_returnOtherMonth.do?EMP_SID=" + empSid, monthParam);
    storeDataToFile(context,queryMonthsHtml, "months.html");
    var monthDoc = Jsoup.parse(queryMonthsHtml);
    var monthsElement = monthDoc.select("#transformTit > li ");
    if(monthsElement==null || undefined == monthsElement){
        logger.info("Citic taskKey = {} 获取已出账单的月份位null,停止抓取已出账单",context.get(LUA_TASK_KEY))
        return
    }
    var monthsList = new ArrayList();
    try {
        for(var i=0;i<monthsElement.size();i++){
            var months = monthsElement.get(i).select("li > a").get(0).text();
            monthsList.add(months)
        }
    }catch (e){
        logger.info("Citic taskKey = {} 获取已出账单的月份位解析失败，",context.get(LUA_TASK_KEY))
    }
    for(var i=0;i<monthsList.size();i++) {
        logger.info("Citic taskKey = {} 开始抓取 {} 月的数据",context.get(LUA_TASK_KEY),i)
        var billAllData = new BillAllData();
        crawlCiticCreditMonthsBill(empSid, cardNo, i, billAllData);
        creditCardAllData.getBills().add(billAllData);
    }

}
/**
 * 抓取每个月的账单数据
 * @param empId
 * @param cardNo
 * @param currentMonth
 * @param billAllDate
 */
function crawlCiticCreditMonthsBill(empSid,cardNo,currentMonth,billAllData) {
    //accountNo=4033920033997406&accoMonth=201802&currencyType=001&startNo=01&crdRecordItem=10&opFlag=1&sFrnCyno=014&qryCrdCurr=001
    //https://i.bank.ecitic.com/perbank6/pb5130_invokeHisDetailBiz.do?EMP_SID=DPHTHAIZEVIDFUIDEXJHDEBWGDCODTBHJCJTBREQ
    billAllData.setBankName("中信银行");
    // billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(formatDate(billdate)));
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBillType("DONE");
    // billAllData.setBillMonth(formatMonth(billdate));//amtPmtdAll
    billAllData.setCashLimit(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setLastPayment(null);
    var param = new HashMap();
    param.put("accountNo", cardNo);
    param.put("accoMonth", currentMonth);
    param.put("currencyType", "001");
    param.put("crdRecordItem", "10");
    param.put("opFlag", "1");
    param.put("sFrnCyno", "014");
    param.put("qryCrdCurr", "001");
    var billDetailHtml= ajax_post("https://i.bank.ecitic.com/perbank6/pb5130_invokeHisDetailBiz.do?EMP_SID=" + empSid);
    storeDataToFile(context,billDetailHtml, "monthsDetail"+currentMonth+".html");
    var billDetailDoc = Jsoup.parse(billDetailHtml);
    var billDetailElement= billDetailDoc.select("");
    var shopping_sheets = billAllData.getShoppingSheets();

    if(billDetailElement!=null&&billDetailElement!=undefined&&billDetailElement.size()>0){
        if(billDetailElement.html().contains("您查询的月份暂无账单数据")){
            logger.info("Citic taskKey = {} ,当前 {} 月无数据",context.get(LUA_TASK_KEY),currentMonth)
            return;
        }
        try {
            for(var i=0;i<billDetailElement.size();i++){
                var order_index=shopping_sheets.size()+1;
                var expense=new Expense();
                var billDetail= billDetailElement.get(i);
                var description = billDetail.select("").get(0).text();//描述
                var amount_money = billDetail.select("").get(0).text().replaceAll(",","");//交易金额
                var currecy = billDetail.select("").get(0).text();//交易币种
                var post_date = billDetail.select("").get(0).text();//结算金额
                var trans_date = billDetail.select("").get(0).text();//交易日期
                var post_date = billDetail.select("").get(0).text();//入账日期
                expense.setDescription(description);
                expense.setCardNum(cardNo.substring(cardNo.length()-4,cardNo.length()));
                var category =  CategoryUtil.getCreditCategory("CITIC", description, amount_money);
                if(StringUtils.isBlank(category)){
                    category ="SHOPPING";
                }
                expense.setCategory();
                expense.setPostDate();//TODO 这里需要格式话
                expense.setTransDate();//TODO 这里需要格式话
                expense.setCurrencyType("CNY");
                expense.setId(UUID.randomUUID.toString());
                expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money));
                expense.setOrderIndex(order_index);

                shopping_sheets.add(expense);
            }
        }catch (e){
            logger.info("Citic taskKey = {} ,解析 {} 月数据出错",context.get(LUA_TASK_KEY),currentMonth)
        }
    }else {
        logger.info("Citic taskKey = {} ,当前 {} 月无数据",context.get(LUA_TASK_KEY),currentMonth)
        return;

    }


}




/**
 * ------------------------------------------------------------------------------------
 * end--------------抓取业务方法--------------end
 * ------------------------------------------------------------------------------------
 */




/**
 *--------------------------------------------------------------------------------------
 * sart-----------------lua的方法-----------------start
 * -------------------------------------------------------------------------------------
 */


var luaFuncs = {
    getCookie: function () {
        var map = new HashMap();
        map.put("method", "getCookie");
        return sendAndReceive(map)
    },
    inputnameAndpassword:function(userName, password){
        var map = new HashMap();
        map.put("method", "inputnameAndpassword");
        map.put("username", userName);
        map.put("password", password);
        return sendAndReceive(map);
    },
    getHtmlGb:function(){
        var map = new HashMap();
        map.put("method", "getHtmlGb");
        return sendAndReceive(map);
    },
    clickLogin: function(){
        var map = new HashMap();
        map.put("method", "clickLogin");
        return sendAndReceive(map);
    },
    setCode:function(code){
        var map = new HashMap();
        map.put("method", "setCode");
        map.put("code", code);
        return sendAndReceive(map);
    }
}
